package 结构型模式.享元;

import java.util.HashMap;
import java.util.Map;

public class FlyWeightTest {
    public static void main(String[] args) {
        FlyWeightFactory flyWeightFactory = new FlyWeightFactory();

        FlyWeight a1 = flyWeightFactory.getFlyWeight("a");
        FlyWeight a2 = flyWeightFactory.getFlyWeight("a");
        FlyWeight a3 = flyWeightFactory.getFlyWeight("a");
        FlyWeight b1 = flyWeightFactory.getFlyWeight("b");
        FlyWeight b2 = flyWeightFactory.getFlyWeight("b");

        a1.operate(new UnFlyWeight("第1次调用a。"));
        a2.operate(new UnFlyWeight("第2次调用a。"));
        a3.operate(new UnFlyWeight("第3次调用a。"));
        b1.operate(new UnFlyWeight("第1次调用b。"));
        b2.operate(new UnFlyWeight("第2次调用b。"));

    }
}

// 享元接口
interface FlyWeight {
    void operate(UnFlyWeight unFlyWeight);
}
// 具体享元
class SpecialFlyWeight implements FlyWeight {

    private String key;

    @Override
    public void operate(UnFlyWeight unFlyWeight) {
        System.out.print("具体享元" + key + "被调用，");
        System.out.println("非享元信息是:" + unFlyWeight.getName());
    }

    public SpecialFlyWeight(String key) {
        this.key = key;
    }
}

// 享元工厂
class FlyWeightFactory {
    private Map<String, FlyWeight> flyWeightMap = new HashMap<String, FlyWeight>();

    FlyWeight getFlyWeight(String key) {
        FlyWeight flyWeight = flyWeightMap.get(key);
        if (flyWeight == null) {
            SpecialFlyWeight specialFlyWeight = new SpecialFlyWeight(key);
            flyWeightMap.put(key, specialFlyWeight);
            return specialFlyWeight;
        } else {
            System.out.println("具体享元" + key + "已经存在，被成功获取！");
        }
        return flyWeight;
    }
}

// 非享元对象
class UnFlyWeight {
    private String name;

    public UnFlyWeight(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
